package edu.hebeu.evil.freshmenguide.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.util.List;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Utils
 * 时间：16-7-8 下午6:07
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：工具类
 ********************************************/
public class Utils
{
    private static Context context;
    private static boolean debug = false;
    private static String tag;

    /**
     * 初始化工具类,写在Application.class
     *
     * @param application
     */
    public static void initUtils(Application application)
    {
        context = application.getApplicationContext();
    }

    /**
     * 获取Context
     *
     * @return
     */
    public static Context getContext()
    {
        return context;
    }

    /**
     * 设置是后开启debug模式
     *
     * @param debug true 开启, false 关闭
     * @param tag   Tag标签信息
     */
    public static void setDebug(boolean debug, String tag)
    {
        Utils.debug = debug;
        Utils.tag = tag;
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Log(String msg)
    {
        Log.i(Utils.tag, msg);
    }

    /**
     * 日志输出,自定义tag
     *
     * @param tag
     * @param msg
     */
    public static void Log(String tag, String msg)
    {
        Log.i(tag, msg);
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    public static void Log(Object msg)
    {
        Log.i(Utils.tag, msg + "");
    }

    /**
     * 日志输出,自定义tag
     *
     * @param tag
     * @param msg
     */
    public static void Log(String tag, Object msg)
    {
        Log.i(tag, msg + "");
    }

    /**
     * Toast打印,短时间
     *
     * @param msg
     */
    public static void Toast(String msg)
    {
        Toast.makeText(Utils.context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * Toast打印,长时间
     *
     * @param msg
     */
    public static void ToastLong(String msg)
    {
        Toast.makeText(Utils.context, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * Toast打印,短时间
     *
     * @param msg
     */
    public static void Toast(Object msg)
    {
        Toast.makeText(Utils.context, msg + "", Toast.LENGTH_SHORT).show();
    }

    /**
     * Toast打印,长时间
     *
     * @param msg
     */
    public static void ToastLong(Object msg)
    {
        Toast.makeText(Utils.context, msg + "", Toast.LENGTH_LONG).show();
    }

    /**
     * 线程休眠
     *
     * @param millis
     */
    public static void Threadsleep(int millis)
    {
        try
        {
            Thread.sleep(millis);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }


    /**
     * Glide图片加载
     *
     * @param url
     * @param imageView
     */
    public static void Glide(String url, ImageView imageView)
    {
        Glide.with(context).load(url).centerCrop().into(imageView);
    }

    /**
     * Glide图片加载
     *
     * @param res
     * @param imageView
     */
    public static void Glide(int res, ImageView imageView)
    {
        Glide.with(context).load(res).centerCrop().into(imageView);
    }

    /**
     * 获取颜色
     *
     * @param res
     * @return
     */
    public static int getColor(int res)
    {
        return context.getResources().getColor(res);
    }

    /**
     * 获取Drawable
     *
     * @param res
     * @return
     */
    public static Drawable getDrawable(int res)
    {
        return context.getResources().getDrawable(res);
    }


    /**
     * dp转px
     *
     * @param dpValue
     * @return
     */
    public static int dpTopx(float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * px转dp
     *
     * @param pxValue
     * @return
     */
    public static int pxTodp(float pxValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 取屏幕宽度
     *
     * @return
     */
    public static int getScreenWidth()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 取屏幕高度
     *
     * @return
     */
    public static int getScreenHeight()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels - getStatusBarHeight();
    }

    /**
     * 取屏幕高度包含状态栏高度
     *
     * @return
     */
    public static int getScreenHeightWithStatusBar()
    {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 取导航栏高度
     *
     * @return
     */
    public static int getNavigationBarHeight()
    {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0)
        {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHeight()
    {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0)
        {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 判断应用是否处于后台状态
     *
     * @return
     */
    public static boolean isBackground()
    {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty())
        {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName()))
                return true;
        }
        return false;
    }

    /**
     * 复制文本到剪贴板
     *
     * @param text
     */
    public static void copyToClipboard(String text)
    {
        if (Build.VERSION.SDK_INT >= 11)
        {
            ClipboardManager cbm = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
            cbm.setPrimaryClip(ClipData.newPlainText(context.getPackageName(), text));
        }
        else
        {
            android.text.ClipboardManager cbm = (android.text.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
            cbm.setText(text);
        }
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference()
    {
        return context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference(String name)
    {
        return context.getSharedPreferences(name, Activity.MODE_PRIVATE);
    }

    /**
     * 获取SharedPreferences
     *
     * @return SharedPreferences
     */
    public static SharedPreferences getSharedPreference(String name, int mode)
    {
        return context.getSharedPreferences(name, mode);
    }

    /**
     * 获取版本名
     *
     * @return
     * @throws Exception
     */
    public static String getVersionName()
    {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try
        {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    /**
     * 获取版本号
     *
     * @return
     * @throws Exception
     */
    public static int getVersionCode()
    {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try
        {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        int version = packInfo.versionCode;
        return version;
    }

    /**
     * 线程操作与UI更新
     */
    public static abstract class SHandler
    {
        public abstract void handler();

        public void thread()
        {
        }

        public void thread(Handler handler)
        {
        }

        public void startByCustom()
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    thread(handler);
                }
            });
            thread.start();
        }

        public void start()
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    thread();
                    handler.sendEmptyMessage(0);
                }
            });
            thread.start();
        }

        public void start(final int sleepTime)
        {
            @SuppressLint("HandlerLeak") final Handler handler = new Handler()
            {
                @Override
                public void handleMessage(Message msg)
                {
                    super.handleMessage(msg);
                    handler();
                }
            };
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        Thread.sleep(sleepTime);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    thread();
                    handler.sendEmptyMessage(0);
                }
            });
            thread.start();
        }
    }


    /**
     * 获取手机IMEI,android 6.0以上需要获取权限
     *
     * @return
     */
    public static String getIMEI()
    {
        return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }
}
